import { DatePipe } from '@angular/common'
let moment = require('moment')

export class RYDateService {
  //
  static timeline(datestamp: string): string {
    //ECMAScript5新增了now()方法，该方法返回当前时间距离1970年1月1日0点UTC的毫秒数。该方法不支持传递参数
    let second = parseInt(datestamp)
    if (isNaN(second) || second <= 0) {
      return this.useZh ? "无法获取数据" : "Unable to obtain data"
    }
    let nowstamp = Date.now()
    let distance = parseInt(((nowstamp - second * 1000) / 1000).toString())  //单位转换成秒

    /**
     * UE Updated.
     * 24小时以内：更新于**点**分
     * 超过24小时：更新于*天前
     */
    if (distance < 60 * 60 * 24) {
      return this.useZh ? RYDateService.dateString((second * 1000).toFixed(), "更新于HH点mm分") : (RYDateService.dateString((second * 1000).toFixed(), "HH:mm") + " updated")
    } else {
      return this.useZh ? ("更新于 " + (distance / 60 / 60 / 24).toFixed() + " 天前") : ((distance / 60 / 60 / 24).toFixed() + " days ago")
    }
  }

  static dateString(datestamp: string, format: string): string {
    //时间戳以毫秒为单位
    let millisecond = parseInt(datestamp)
    if (isNaN(millisecond)) {
      return ""
    }
    let date = new Date(millisecond)
    let datePipe = new DatePipe("en-US")
    let dateStr = datePipe.transform(date, format)
    return dateStr
  }

  static dateToString(date: Date, format: string): string {
    if (date == undefined) {
      return ""
    }
    return moment(date).format(format)
  }

  static dateFromString(dateStr: string, format: string): Date | null {
    if (dateStr == undefined) {
      return null
    }
    if (dateStr.length == 0) {
      return null
    }
    return moment(dateStr, format)
  }

  static weekday(datestamp: string): string {
    //时间戳以毫秒为单位
    let millisecond = parseInt(datestamp)
    if (isNaN(millisecond)) {
      return ""
    }
    let date = new Date(millisecond)
    let weekday = date.getDay()
    switch (weekday) {
      case 0: return this.useZh ? "周日" : "Sun"
      case 1: return this.useZh ? "周一" : "Mon"
      case 2: return this.useZh ? "周二" : "Tue"
      case 3: return this.useZh ? "周三" : "Wed"
      case 4: return this.useZh ? "周四" : "Thu"
      case 5: return this.useZh ? "周五" : "Fri"
      case 6: return this.useZh ? "周六" : "Sat"
      default: return this.useZh ? "未知" : "Unknown"
    }
  }

  static hour(datestamp: string): string {
    let millisecond = parseInt(datestamp)
    if (isNaN(millisecond)) {
      return ""
    }
    let date = new Date(millisecond)
    return date.getHours().toString() + (this.useZh ? "点" : ":00")
  }

  static useZh: boolean = false
}
